#include "archivedownloader.h"
#include <QDirIterator>
#include "Utils.h"

ArchiveDownloader::ArchiveDownloader(QString url, QString target,QObject *parent) : QObject(parent)
{
    this->url = url;
    this->target = target;

    t = new QTemporaryDir();


    p = new QProcess();
    p->setProgram("wget");
    p->setWorkingDirectory(t->path());

    QStringList args;
    args << url;
    p->setArguments(args);

    connect(p, SIGNAL(finished(int)), this, SLOT(processFinished()));
    phase = 'd';

    p->start();
}

void ArchiveDownloader::processFinished()
{
    if(phase=='d')
    {
        QDir dir(t->path());
        QDirIterator it(dir);
        QString fileName;
        int count=0;
        while (it.hasNext()) {
            it.next();
            QString file = it.fileName();

            if (file == "." || file == "..") continue;
            fileName = file;
            count++;
        }
        if(count==1) {
            p = new QProcess();
            p->setProgram("unar");//use unp if unar is not installed
            p->setWorkingDirectory(t->path());

            QStringList args;
            args << fileName;
            p->setArguments(args);

            connect(p, SIGNAL(finished(int)), this, SLOT(processFinished()));
            phase = 'u';

            p->start();
        }
    }
    if(phase=='u')
    {
        QDir dir(t->path());
        QDirIterator it(dir);
        QString fileName;
        int count=0;
        while (it.hasNext()) {
            it.next();
            QString file = it.fileName();

            if (file == "." || file == "..") continue;
            if(QFileInfo(t->path()+"/"+file).isDir()) {
                fileName = file;
                count++;
            }
        }
        if(count==1)
        {
            DEVLOG_INFO("unpacked dir"<<fileName);
            dir.rename(fileName,target+"/"+fileName);
            emit done();
        }
        //delete t
    }
}
